package jishiti.counttxtfile;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 两个线程交替打出1个字符，可以使用锁，下面是不使用锁的方法
 */
public class AtomicInteger1 {
    static AtomicInteger threadNo = new AtomicInteger(1);
    public static void main(String[] args) {
        char [] a = "ABCDEFG".toCharArray();
        char [] b = "1234567".toCharArray();
        new Thread(()->{
            for (char c : a) {
                while ((threadNo.get()&1)!=1){}//n&1比n%2更快，效果一样
                System.out.println(c);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                threadNo.set(2);
            }
        },"t1").start();
        new Thread(()->{
            for (char c : b) {
                while ((threadNo.get()&1)!=0){}
                System.out.println(c);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                threadNo.set(1);
            }
        },"t2").start();
     }
}
